<template>
  <div class="account-manage">
    <el-card>
      <el-tabs v-model="activeTab">
        <!-- 交易账号Tab -->
        <el-tab-pane label="交易账号" name="trade">
          <!-- 站点切换Tab -->
          <div class="site-tabs-bar">
            <el-tabs v-model="activeSiteTab" type="card" class="site-tabs-fixed">
              <el-tab-pane label="全部" name="all" />
              <el-tab-pane label="煤炉" name="mercari" />
              <el-tab-pane label="雅虎日拍" name="yahoo_auction" />
              <el-tab-pane label="雅虎闲置" name="yahoo_flea" />
              <el-tab-pane label="煤炉闲置" name="mercari_flea" />
            </el-tabs>
            <el-select
              v-model="siteSelectValue"
              filterable
              clearable
              placeholder="切换站点"
              class="site-select"
              style="width: 180px; margin-left: 12px;"
            >
              <el-option
                v-for="site in siteList.filter(s => s.enabled && !['mercari', 'yahoo_auction', 'yahoo_flea', 'mercari_flea'].includes(s.value))"
                :key="site.value"
                :label="site.label"
                :value="site.value"
              />
            </el-select>
            <el-button class="site-manage-btn" @click="goToSiteManage">
              <el-icon><Setting /></el-icon>
              管理站点
            </el-button>
          </div>

          <el-form :inline="true" :model="tradeSearchForm" class="search-form" style="margin-top: 16px; margin-bottom: 8px;">
            <el-form-item label="交易账号">
              <el-input v-model="tradeSearchForm.account" placeholder="请输入交易账号" clearable style="width: 140px;" />
            </el-form-item>
            <el-form-item label="账号昵称">
              <el-input v-model="tradeSearchForm.accountNickname" placeholder="请输入账号昵称" clearable style="width: 140px;" />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="tradeSearchForm.phone" placeholder="请输入手机号" clearable style="width: 140px;" />
            </el-form-item>
            <el-form-item label="辅助科目">
              <el-input v-model="tradeSearchForm.payAccount" placeholder="请输入辅助科目" clearable style="width: 140px;" />
            </el-form-item>
            <el-form-item label="站点">
              <el-select v-model="tradeSearchForm.site" placeholder="请选择站点" clearable style="width: 140px;">
                <el-option label="全部" value="" />
                <el-option 
                  v-for="site in allSites" 
                  :key="site.value" 
                  :label="site.label" 
                  :value="site.value" 
                />
              </el-select>
            </el-form-item>
            <el-form-item label="绑定用户">
              <el-input v-model="tradeSearchForm.user" placeholder="请输入绑定用户" clearable style="width: 120px;" />
            </el-form-item>
            <el-form-item label="绑定服务器">
              <el-input v-model="tradeSearchForm.server" placeholder="请输入服务器名称/IP" clearable style="width: 140px;" />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="tradeSearchForm.status" placeholder="全部" clearable style="width: 100px;">
                <el-option label="启用" value="启用" />
                <el-option label="禁用" value="禁用" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="resetTradeSearch">重置</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="openTradeDialog('add')">新增</el-button>
            </el-form-item>

          </el-form>
          

          


          <!-- 表格右上角按钮 -->
          <div style="display: flex; justify-content: flex-end; margin-bottom: 8px;">
            <el-button 
              type="info"
              @click="toggleDisabledAccounts"
              size="small"
              plain
              style="border-color: #909399; color: #606266;"
            >
              {{ showDisabledAccounts ? '隐藏禁用账号' : '显示禁用账号' }}
            </el-button>
          </div>
          
          <el-table :data="pagedTradeAccounts" style="width: 100%">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="site" label="站点" width="100">
              <template #default="scope">
                <el-tag :type="getSiteTagType(scope.row.site)" size="small">
                  {{ getSiteDisplayName(scope.row.site) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="account" label="交易账号" width="140" />
            <el-table-column prop="accountNickname" label="账号昵称" width="120">
              <template #default="scope">
                <span>{{ scope.row.accountNickname || '未设置' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" width="120">
              <template #default="scope">
                <span>{{ scope.row.phone || '未设置' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="password" label="密码" width="100">
              <template #default="scope">
                <span>{{ scope.row.showPassword ? scope.row.password : '******' }}</span>
                <el-button
                  size="small"
                  text
                  @click="togglePasswordVisibility(scope.row)"
                  style="margin-left: 8px;"
                >
                  <el-icon><View v-if="!scope.row.showPassword" /><Hide v-else /></el-icon>
                </el-button>
              </template>
            </el-table-column>
                          <el-table-column prop="payAccount" label="辅助科目" width="200">
              <template #default="scope">
                <span>{{ getFormattedAuxiliarySubject(scope.row.payAccount) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="bindUsers" label="绑定用户" width="120">
              <template #default="scope">
                <div v-if="scope.row.bindUsers && scope.row.bindUsers.length > 0">
                  <el-tag 
                    type="primary" 
                    size="small"
                    style="cursor: pointer;"
                    @click="goToTradeUsersDetail(scope.row)"
                  >
                    {{ scope.row.bindUsers.length }} 个用户
                  </el-tag>

                </div>
                <span v-else style="color: #999;">未绑定</span>
              </template>
            </el-table-column>
            <el-table-column prop="bindServer" label="绑定服务器" width="160">
              <template #default="scope">
                <div v-if="scope.row.bindServer" style="display: flex; align-items: center; gap: 8px;">
                  <span>{{ scope.row.bindServer }}</span>
                </div>
                <span v-else style="color: #999;">未绑定</span>
              </template>
            </el-table-column>
            <el-table-column label="更换交易账号" width="140">
              <template #default="scope">
                <el-button 
                  size="small" 
                  type="primary" 
                  text 
                  @click="switchTradeAccount(scope.row)"
                  :disabled="!scope.row.bindUsers || scope.row.bindUsers.length === 0"
                >
                  <el-icon><Refresh /></el-icon>
                  一键更换
                </el-button>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="150" show-overflow-tooltip />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <div style="display: flex; gap: 8px; align-items: center;">
                  <el-button size="small" style="min-width: unset;" @click="showTradeDetail(scope.row)">详情</el-button>
                  <el-button size="small" style="min-width: unset;" @click="openTradeDialog('edit', scope.row, scope.$index)">编辑</el-button>
                  <el-button
                    size="small"
                    style="min-width: unset;"
                    :type="scope.row.status === '启用' ? 'warning' : 'success'"
                    @click="toggleTradeStatus(scope.row)"
                  >
                    {{ scope.row.status === '启用' ? '禁用' : '启用' }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-model:current-page="tradePage.current"
            v-model:page-size="tradePage.size"
            :total="filteredTradeAccounts.length"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 50]"
            style="margin-top: 12px; text-align: right;"
          />
          <!-- 新增/编辑弹窗 -->
          <el-dialog v-model="tradeDialog.visible" :title="tradeDialog.mode === 'add' ? '新增交易账号' : '编辑交易账号'" width="500px" :close-on-click-modal="false">
            <el-form :model="tradeDialog.form" label-width="100px">
              <el-form-item label="绑定站点" required>
                <el-select v-model="tradeDialog.form.site" placeholder="请选择站点" style="width: 100%">
                  <el-option
                    v-for="site in allSites"
                    :key="site.value"
                    :label="site.label"
                    :value="site.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="交易账号" required>
                <el-input v-model="tradeDialog.form.account" placeholder="请输入交易账号" />
              </el-form-item>
              <el-form-item label="账号昵称" required>
                <el-input v-model="tradeDialog.form.accountNickname" placeholder="请输入账号昵称" />
              </el-form-item>
              <el-form-item label="手机号" required>
                <el-input v-model="tradeDialog.form.phone" placeholder="请输入手机号" />
              </el-form-item>
              <el-form-item label="密码" required>
                <el-input v-model="tradeDialog.form.password" type="password" show-password placeholder="请输入密码" />
              </el-form-item>
              <el-form-item label="辅助科目" required>
                <div class="pay-accounts-container">
                  <div 
                    v-for="(payAccount, index) in tradeDialog.form.payAccounts" 
                    :key="index" 
                    class="pay-account-item"
                  >
                    <el-select 
                      v-model="payAccount.cardNo" 
                      placeholder="请选择辅助科目" 
                      style="width: calc(100% - 40px);"
                    >
                      <el-option
                        v-for="bankAccount in enabledBankAccounts"
                        :key="bankAccount.cardNo"
                        :label="`${bankAccount.abbreviatedSubjectName} - ${bankAccount.subjectName} - ${maskPayAccount(bankAccount.cardNo)}`"
                        :value="bankAccount.cardNo"
                        :disabled="tradeDialog.form.payAccounts.some((pa, i) => i !== index && pa.cardNo === bankAccount.cardNo)"
                      />
                    </el-select>
                    <el-button 
                      v-if="tradeDialog.form.payAccounts.length > 1"
                      @click="removePayAccount(index)" 
                      type="danger" 
                      size="small" 
                      style="margin-left: 8px;"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                  <el-button 
                    @click="addPayAccount" 
                    type="primary" 
                    size="small" 
                    style="margin-top: 8px;"
                  >
                    <el-icon><Plus /></el-icon>
                    添加辅助科目
                  </el-button>
                </div>
              </el-form-item>
              <el-form-item label="绑定用户">
                <el-input
                  v-model="userIdBatchInput"
                  placeholder="输入用户ID，支持逗号、空格、换行分隔，回车或点击添加"
                  @keyup.enter="handleBatchUserInput"
                  style="width: 260px; margin-bottom: 8px;"
                />
                <el-button @click="handleBatchUserInput" size="small" style="margin-left: 8px;">添加</el-button>
                <div style="margin: 8px 0 8px 0; display: flex; flex-wrap: wrap; gap: 4px; max-height: 48px; overflow: hidden;">
                  <el-tag
                    v-for="user in tradeDialog.form.bindUsers"
                    :key="user.id"
                    closable
                    @close="removeUser(user.id)"
                    size="small"
                  >
                    {{ user.nickname ? user.nickname + '（' + user.id + '）' : user.id }}
                  </el-tag>
                  <span v-if="!tradeDialog.form.bindUsers || tradeDialog.form.bindUsers.length === 0" style="color: #999; font-size: 12px;">
                    暂无绑定用户
                  </span>
                </div>
              </el-form-item>
              <el-form-item label="绑定服务器" required>
                <el-select v-model="tradeDialog.form.bindServer" placeholder="请选择绑定服务器" style="width: 100%">
                  <el-option v-for="server in availableServers" :key="server.value" :label="server.label" :value="server.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="备注" required>
                <el-input v-model="tradeDialog.form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="tradeDialog.visible = false">取消</el-button>
              <el-button type="primary" @click="saveTrade">保存</el-button>
            </template>
          </el-dialog>
          <!-- 批量导入弹窗 -->
          <!-- <el-dialog v-model="tradeImportDialog" title="批量导入交易账号" width="400px" :close-on-click-modal="false">
            <el-upload
              class="excel-uploader"
              drag
              :show-file-list="false"
              :before-upload="beforeTradeExcelUpload"
              accept=".xlsx,.xls"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将Excel文件拖到此处，或点击上传</div>
            </el-upload>
            <div style="color: #888; font-size: 13px; margin-top: 8px;">仅支持xlsx/xls，字段：站点、交易账号、密码、辅助科目、绑定用户、绑定服务器、备注</div>
            <template #footer>
              <el-button @click="tradeImportDialog = false">关闭</el-button>
            </template>
          </el-dialog> -->

          <!-- 站点管理弹窗 -->
          <!-- <el-dialog v-model="siteManageDialog" title="站点管理" width="700px" :close-on-click-modal="false">
            <div style="margin-bottom: 16px; display: flex; justify-content: space-between; align-items: center;">
              <div>
                <el-button type="primary" @click="openSiteDialog('add')">
                  <el-icon><Plus /></el-icon>
                  新增站点
                </el-button>
              </div>
              <div style="color: #666; font-size: 14px;">
                共 {{ allSites.length }} 个站点
              </div>
            </div>

            <el-table :data="allSites" style="width: 100%" border>
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="label" label="站点名称" width="180" />
              <el-table-column prop="value" label="站点标识" width="180" />
              <el-table-column prop="description" label="站点描述" show-overflow-tooltip />
              <el-table-column prop="accountCount" label="关联账号数" width="120">
                <template #default="scope">
                  <el-tag type="warning" size="small">{{ getAccountCountBySite(scope.row.value) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="80">
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.enabled"
                    @change="toggleSiteStatus(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="140">
                <template #default="scope">
                  <el-button
                    size="small"
                    @click="openSiteDialog('edit', scope.row, scope.$index)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteSite(scope.$index, scope.row)"
                    :disabled="getAccountCountBySite(scope.row.value) > 0"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <template #footer>
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <div style="color: #666; font-size: 12px;">
                  提示：有关联账号的站点不可删除
                </div>
                <el-button @click="siteManageDialog = false">关闭</el-button>
              </div>
            </template>
          </el-dialog> -->

          <!-- 新增/编辑站点弹窗 -->
          <el-dialog v-model="siteDialog.visible" :title="siteDialog.mode === 'add' ? '新增站点' : '编辑站点'" width="500px" :close-on-click-modal="false">
            <el-form :model="siteDialog.form" :rules="siteFormRules" ref="siteFormRef" label-width="100px">
              <el-form-item label="站点名称" prop="label" required>
                <el-input
                  v-model="siteDialog.form.label"
                  placeholder="请输入站点名称，如：亚马逊日本"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item label="站点标识" prop="value" required>
                <el-input
                  v-model="siteDialog.form.value"
                  placeholder="请输入站点标识，如：amazon_jp（英文、数字、下划线）"
                  maxlength="30"
                  show-word-limit
                />
                <div style="color: #999; font-size: 12px; margin-top: 4px;">
                  站点标识用于系统内部识别，建议使用英文、数字和下划线组合
                </div>
              </el-form-item>
              <el-form-item label="站点描述" prop="description">
                <el-input
                  v-model="siteDialog.form.description"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入站点描述信息（可选）"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item label="站点URL" prop="url">
                <el-input
                  v-model="siteDialog.form.url"
                  placeholder="请输入站点网址（可选）"
                />
              </el-form-item>
              <el-form-item label="启用状态">
                <el-switch v-model="siteDialog.form.enabled" />
                <span style="margin-left: 8px; color: #666; font-size: 12px;">
                  {{ siteDialog.form.enabled ? '启用' : '禁用' }}
                </span>
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="siteDialog.visible = false">取消</el-button>
              <el-button type="primary" @click="saveSite">保存</el-button>
            </template>
          </el-dialog>

          <!-- 服务器切换弹窗 -->
          <el-dialog v-model="serverSwitchDialog.visible" title="切换服务器" width="400px" :close-on-click-modal="false">
            <div style="margin-bottom: 16px;">
              <span>当前账号：</span>
              <el-tag>{{ serverSwitchDialog.currentAccount }}</el-tag>
            </div>
            <div style="margin-bottom: 16px;">
              <span>当前服务器：</span>
              <el-tag type="info">{{ serverSwitchDialog.currentServer || '未绑定' }}</el-tag>
            </div>
            <el-form label-width="80px">
              <el-form-item label="新服务器" required>
                <el-select v-model="serverSwitchDialog.newServer" placeholder="请选择新服务器" style="width: 100%">
                  <el-option v-for="server in availableServers" :key="server.value" :label="server.label" :value="server.value" />
                </el-select>
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="serverSwitchDialog.visible = false">取消</el-button>
              <el-button type="primary" @click="confirmSwitchServer">确认切换</el-button>
            </template>
          </el-dialog>

          <!-- 交易账号切换弹窗 -->
          <el-dialog v-model="tradeAccountSwitchDialog.visible" title="一键更换交易账号" width="500px" :close-on-click-modal="false">
            <div style="margin-bottom: 16px;">
              <div style="color: #666; font-size: 12px; margin-bottom: 8px;">
                将当前账号的登录信息更换为其他可用账号，绑定用户保持不变
              </div>
              <span>当前账号：</span>
              <el-tag>{{ tradeAccountSwitchDialog.currentAccount }}</el-tag>
            </div>
            <div style="margin-bottom: 16px;">
              <span>绑定用户：</span>
              <div style="margin-top: 8px;">
                <el-tag 
                  v-for="user in tradeAccountSwitchDialog.currentUsers" 
                  :key="user.id" 
                  size="small" 
                  type="info"
                  style="margin-right: 4px; margin-bottom: 4px;"
                >
                  {{ user.nickname || user.id }}
                </el-tag>
                <span v-if="!tradeAccountSwitchDialog.currentUsers || tradeAccountSwitchDialog.currentUsers.length === 0" style="color: #999;">无绑定用户</span>
              </div>
            </div>
            <el-form label-width="100px">
              <el-form-item label="目标账号" required>
                <div style="margin-bottom: 8px; color: #666; font-size: 12px;">
                  只能选择与当前账号相同站点的启用账号
                </div>
                <el-select v-model="tradeAccountSwitchDialog.newAccount" placeholder="请选择目标交易账号" style="width: 100%">
                  <el-option 
                    v-for="account in availableTradeAccounts" 
                    :key="account.account" 
                    :label="`${account.account} (${getSiteDisplayName(account.site)})`" 
                    :value="account.account" 
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <div style="margin-top: 16px; padding: 12px; background-color: #f0f9ff; border: 1px solid #b3d8ff; border-radius: 4px;">
              <div style="color: #1890ff; font-size: 12px;">
                <strong>业务场景：</strong>
                <ul style="margin: 8px 0 0 16px; padding: 0;">
                  <li>当前交易账号被日本网站封号，无法继续下单</li>
                  <li>更换为其他可用账号的登录信息</li>
                  <li>绑定用户保持不变，用户下单不受影响</li>
                  <li>确保用户购物体验不受影响</li>
                </ul>
              </div>
            </div>
            <template #footer>
              <el-button @click="tradeAccountSwitchDialog.visible = false">取消</el-button>
              <el-button type="primary" @click="confirmSwitchTradeAccount">确认更换</el-button>
            </template>
          </el-dialog>

          <!-- 用户转移对话框 -->
          <el-dialog v-model="userTransferDialog.visible" title="转移绑定用户" width="500px" :close-on-click-modal="false">
            <div style="margin-bottom: 16px;">
              <div style="color: #666; font-size: 12px; margin-bottom: 8px;">
                禁用交易账号前，需要先转移绑定用户到其他可用账号
              </div>
              <span>当前账号：</span>
              <el-tag type="warning">{{ userTransferDialog.currentAccount }}</el-tag>
            </div>
            <div style="margin-bottom: 16px;">
              <span>绑定用户：</span>
              <div style="margin-top: 8px;">
                <el-tag 
                  v-for="user in userTransferDialog.currentUsers" 
                  :key="user.id" 
                  size="small" 
                  type="info"
                  style="margin-right: 4px; margin-bottom: 4px;"
                >
                  {{ user.nickname || user.id }}
                </el-tag>
                <span v-if="!userTransferDialog.currentUsers || userTransferDialog.currentUsers.length === 0" style="color: #999;">无绑定用户</span>
              </div>
            </div>
            <el-form label-width="100px">
              <el-form-item label="目标账号" required>
                <div style="margin-bottom: 8px; color: #666; font-size: 12px;">
                  只能选择与当前账号相同站点的启用账号
                </div>
                <el-select v-model="userTransferDialog.targetAccount" placeholder="请选择目标交易账号" style="width: 100%">
                  <el-option 
                    v-for="account in availableTransferAccounts" 
                    :key="account.account" 
                    :label="`${account.account} (${getSiteDisplayName(account.site)})`" 
                    :value="account.account" 
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <div style="margin-top: 16px; padding: 12px; background-color: #fff2e8; border: 1px solid #ffbb96; border-radius: 4px;">
              <div style="color: #d46b08; font-size: 12px;">
                <strong>操作说明：</strong>
                <ul style="margin: 8px 0 0 16px; padding: 0;">
                  <li>转移后，当前账号将被禁用</li>
                  <li>绑定用户将转移到目标账号</li>
                  <li>用户下单时将使用目标账号</li>
                  <li>此操作不可撤销，请谨慎操作</li>
                </ul>
              </div>
            </div>
            <template #footer>
              <el-button @click="userTransferDialog.visible = false">取消</el-button>
              <el-button type="primary" @click="confirmUserTransfer">确认转移</el-button>
            </template>
          </el-dialog>
        </el-tab-pane>
                <!-- 会计科目Tab -->
        <el-tab-pane label="会计科目" name="bank">
          <!-- 验证弹窗 -->
          <el-dialog v-model="bankVerificationDialog.visible" title="安全验证" width="500px" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
            <div style="text-align: center; margin-bottom: 20px;">
              <el-icon size="48" color="#409eff"><Warning /></el-icon>
              <div style="margin-top: 12px; font-size: 16px; font-weight: 500; color: #303133;">
                会计科目信息需要安全验证
              </div>
              <div style="margin-top: 8px; color: #666; font-size: 14px;">
                验证码将发送到您的手机号
              </div>
            </div>
            
            <el-form :model="bankVerificationDialog.form" :rules="bankVerificationRules" ref="bankVerificationFormRef" label-width="100px">
              <el-form-item label="当前用户">
                <el-input 
                  :value="`${currentUser.name} (${currentUser.countryCode} ${currentUser.mobile})`" 
                  disabled 
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item label="验证码" prop="code">
                <div style="display: flex; gap: 8px;">
                  <el-input v-model="bankVerificationDialog.form.code" placeholder="请输入验证码" style="flex: 1;" />
                  <el-button 
                    :disabled="bankVerificationDialog.countdown > 0" 
                    @click="sendBankVerificationCode"
                    style="width: 120px;"
                  >
                    {{ bankVerificationDialog.countdown > 0 ? `${bankVerificationDialog.countdown}s` : '获取验证码' }}
                  </el-button>
                </div>
              </el-form-item>
            </el-form>
            
            <template #footer>
              <div style="text-align: center;">
                <el-button @click="cancelBankVerification" type="info">取消</el-button>
                <el-button type="primary" @click="confirmBankVerification">验证</el-button>
              </div>
            </template>
          </el-dialog>
          
          <!-- 会计科目内容 -->
          <div v-if="bankVerified">
            <!-- 自动加密倒计时提示 -->
            <div v-if="encryptCountdown > 0" style="margin-bottom: 16px; padding: 12px; background-color: #fff3cd; border: 1px solid #ffeaa7; border-radius: 4px; display: flex; align-items: center;">
              <div style="display: flex; align-items: center; gap: 8px;">
                <el-icon color="#f39c12"><Warning /></el-icon>
                <span style="color: #856404; font-size: 14px;">
                  页面将在 {{ Math.floor(encryptCountdown / 60) }}:{{ String(encryptCountdown % 60).padStart(2, '0') }} 后自动加密
                </span>
              </div>
            </div>
            
            <div class="table-actions">
              <el-input v-model="bankSearch" placeholder="搜索银行卡号/安全码" clearable style="width: 220px; margin-right: 12px;" />
              <el-select v-model="bankStatusFilter" placeholder="状态筛选" clearable style="width: 120px; margin-right: 12px;">
                <el-option label="全部" value="" />
                <el-option label="启用" value="启用" />
                <el-option label="禁用" value="禁用" />
              </el-select>
              <el-button type="primary" @click="openBankDialog('add')">新增</el-button>
              <el-button v-if="bankSearch || bankStatusFilter" @click="resetBankFilter" style="margin-left: 8px;">重置</el-button>
            </div>
            
            <!-- 会计科目表格右上角按钮 -->
            <div style="display: flex; justify-content: flex-end; margin-bottom: 8px;">
              <el-button 
                type="info"
                @click="toggleDisabledBankAccounts"
                size="small"
                plain
                :disabled="bankStatusFilter !== ''"
                style="border-color: #909399; color: #606266;"
              >
                {{ showDisabledBankAccounts ? '隐藏禁用账号' : '显示禁用账号' }}
              </el-button>
            </div>
            
            <el-table :data="pagedBankAccounts" style="width: 100%">
              <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="formalSubjectId" label="正式科目ID" width="120" />
                  <el-table-column prop="formalSubjectName" label="正式科目名" width="120" />
                  <el-table-column prop="abbreviatedSubjectName" label="略科目名" width="120" />
                  <el-table-column prop="subjectId" label="辅助科目ID" width="120" />
                  <el-table-column prop="subjectName" label="辅助科目名" width="120" />
              <el-table-column prop="cardNo" label="银行卡号" width="180" />
              <el-table-column prop="safeCode" label="安全码" width="100" />
              <el-table-column prop="expiryDate" label="有效期" width="120" />
              <el-table-column label="绑定站点" width="200">
                <template #default="scope">
                  <div class="sites-display">
                    <el-tag 
                      v-for="siteInfo in getBankBoundSites(scope.row)" 
                      :key="siteInfo.site" 
                      size="small" 
                      style="margin-right: 4px;"
                    >
                      {{ siteInfo.site }}
                    </el-tag>
                    <el-tag 
                      v-if="getBankBoundSites(scope.row).length > 2" 
                      size="small" 
                      type="info"
                      @click="goToBankSitesDetail(scope.row)"
                      style="cursor: pointer;"
                    >
                      +{{ getBankBoundSites(scope.row).length - 2 }}
                    </el-tag>
                    <el-tag 
                      v-if="getBankBoundSites(scope.row).length <= 2 && getBankBoundSites(scope.row).length > 0" 
                      size="small" 
                      type="info"
                      @click="goToBankSitesDetail(scope.row)"
                      style="cursor: pointer;"
                  >
                    详情
                  </el-tag>
                    <span v-if="getBankBoundSites(scope.row).length === 0" style="color: #999; font-size: 12px;">
                      未绑定
                    </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="编辑操作" width="100">
                <template #default="scope">
                    <el-button size="small" @click="openBankDialog('edit', scope.row, scope.$index)">编辑</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              v-model:current-page="bankPage.current"
              v-model:page-size="bankPage.size"
              :total="filteredBankAccounts.length"
              layout="total, prev, pager, next, sizes"
              :page-sizes="[10, 20, 50]"
              style="margin-top: 12px; text-align: right;"
            />
            
            <!-- 新增/编辑弹窗 -->
            <el-dialog v-model="bankDialog.visible" :title="bankDialog.mode === 'add' ? '新增会计科目' : '编辑会计科目'" width="600px" :close-on-click-modal="false">
              <el-form :model="bankDialog.form" label-width="120px">
                <el-form-item label="正式科目ID">
                  <el-input v-model="bankDialog.form.formalSubjectId" placeholder="请输入正式科目ID" />
                </el-form-item>
                <el-form-item label="正式科目名">
                  <el-input v-model="bankDialog.form.formalSubjectName" placeholder="请输入正式科目名" />
                </el-form-item>
                <el-form-item label="略科目名">
                  <el-input v-model="bankDialog.form.abbreviatedSubjectName" placeholder="请输入略科目名" />
                </el-form-item>
                              <el-form-item label="辅助科目ID">
                <el-input v-model="bankDialog.form.subjectId" placeholder="请输入辅助科目ID" />
              </el-form-item>
              <el-form-item label="辅助科目名">
                <el-input v-model="bankDialog.form.subjectName" placeholder="请输入辅助科目名" />
                </el-form-item>
                <el-form-item label="银行卡号">
                  <el-input v-model="bankDialog.form.cardNo" placeholder="请输入银行卡号" />
                </el-form-item>
                <el-form-item label="安全码">
                  <el-input v-model="bankDialog.form.safeCode" placeholder="请输入安全码" />
                </el-form-item>
                <el-form-item label="有效期">
                  <el-input v-model="bankDialog.form.expiryDate" placeholder="格式：MM/YY" />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="bankDialog.visible = false">取消</el-button>
                <el-button type="primary" @click="saveBank">保存</el-button>
              </template>
            </el-dialog>
            

          </div>
          
          <!-- 无权限提示 -->
          <div v-else-if="activeTab === 'bank' && !hasPermissionEmployee()" style="text-align: center; padding: 60px 20px;">
            <el-icon size="64" color="#f56c6c"><Warning /></el-icon>
            <div style="margin-top: 16px; font-size: 18px; color: #303133; font-weight: 500;">
              权限不足
            </div>
            <div style="margin-top: 8px; color: #666; font-size: 14px;">
              您没有访问会计科目的权限，请联系管理员
            </div>
          </div>
          
          <!-- 批量导入弹窗 -->
          <!-- <el-dialog v-model="bankImportDialog" title="批量导入会计科目" width="400px" :close-on-click-modal="false">
            <el-input v-model="bankImportText" type="textarea" :rows="6" placeholder="每行一个账号，格式：银行卡号,安全码" />
            <template #footer>
              <el-button @click="bankImportDialog = false">取消</el-button>
              <el-button type="primary" @click="doBankImport">导入</el-button>
            </template>
          </el-dialog> -->
        </el-tab-pane>
        <!-- 服务器账号Tab -->
        <el-tab-pane label="服务器账号" name="server">
          <div class="table-actions">
            <el-input v-model="serverSearch" placeholder="搜索名称/IP/备注" clearable style="width: 220px; margin-right: 12px;" />
            <el-button type="primary" @click="openServerDialog('add')">新增</el-button>
            <!-- <el-button @click="serverImportDialog = true" style="margin-left: 8px;">批量导入</el-button> -->
          </div>
          <el-table :data="pagedServerAccounts" style="width: 100%">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="name" label="名称" width="120" />
            <el-table-column prop="ip" label="服务器IP" width="160" />
            <el-table-column prop="status" label="状态" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.status === '启用' ? 'success' : 'info'">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="180" />
            <el-table-column label="操作" width="140">
              <template #default="scope">
                <el-button size="small" @click="openServerDialog('edit', scope.row, scope.$index)">编辑</el-button>
                <el-button size="small" :type="scope.row.status === '启用' ? 'warning' : 'success'" @click="toggleServerStatus(scope.row)">
                  {{ scope.row.status === '启用' ? '禁用' : '启用' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-model:current-page="serverPage.current"
            v-model:page-size="serverPage.size"
            :total="filteredServerAccounts.length"
            layout="total, prev, pager, next, sizes"
            :page-sizes="[10, 20, 50]"
            style="margin-top: 12px; text-align: right;"
          />
          <!-- 新增/编辑弹窗 -->
          <el-dialog v-model="serverDialog.visible" :title="serverDialog.mode === 'add' ? '新增服务器账号' : '编辑服务器账号'" width="400px" :close-on-click-modal="false">
            <el-form :model="serverDialog.form" label-width="90px">
              <el-form-item label="名称">
                <el-input v-model="serverDialog.form.name" />
              </el-form-item>
              <el-form-item label="服务器IP">
                <el-input v-model="serverDialog.form.ip" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="serverDialog.form.remark" />
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="serverDialog.visible = false">取消</el-button>
              <el-button type="primary" @click="saveServer">保存</el-button>
            </template>
          </el-dialog>
          <!-- 批量导入弹窗 -->
          <!-- <el-dialog v-model="serverImportDialog" title="批量导入服务器账号" width="400px" :close-on-click-modal="false">
            <el-input v-model="serverImportText" type="textarea" :rows="6" placeholder="每行一个账号，格式：名称,IP,备注" />
            <template #footer>
              <el-button @click="serverImportDialog = false">取消</el-button>
              <el-button type="primary" @click="doServerImport">导入</el-button>
            </template>
          </el-dialog> -->
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog v-model="tradeDetailDialog.visible" title="账号详情" width="700px" :close-on-click-modal="false">
      <el-descriptions :column="1" border v-if="tradeDetailDialog.data">
        <el-descriptions-item label="交易账号">{{ tradeDetailDialog.data.account }}</el-descriptions-item>
                    <el-descriptions-item label="辅助科目">{{ maskPayAccount(tradeDetailDialog.data.payAccount) }}</el-descriptions-item>
        <el-descriptions-item label="绑定用户">
          <div v-if="tradeDetailDialog.data.bindUsers && tradeDetailDialog.data.bindUsers.length > 0">
            <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
              <el-tag 
                type="primary" 
                size="small"
                style="cursor: pointer;"
                @click="goToTradeUsersDetail(tradeDetailDialog.data)"
              >
                {{ tradeDetailDialog.data.bindUsers.length }} 个用户
              </el-tag>
              <span style="color: #666; font-size: 12px;">点击查看详情</span>
            </div>
            <div style="color: #666; font-size: 12px;">
              绑定用户：{{ tradeDetailDialog.data.bindUsers.map((u: any) => u.nickname ? `${u.nickname}（${u.id}）` : u.id).join('、') }}
            </div>
          </div>
          <span v-else style="color: #999;">未绑定</span>
        </el-descriptions-item>
        <el-descriptions-item label="绑定服务器">{{ tradeDetailDialog.data.bindServer || '未绑定' }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ tradeDetailDialog.data.remark }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="tradeDetailDialog.data.status === '启用' ? 'success' : 'info'">{{ tradeDetailDialog.data.status }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="tradeDetailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Setting, View, Hide, Refresh, Plus, Warning, Delete } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'
import { useRouter } from 'vue-router'
import { tradeAccounts } from '@/mock/tradeAccounts'
import { onMounted } from 'vue'

const activeTab = ref('trade')

// 处理URL参数，设置默认tab
onMounted(() => {
  const urlParams = new URLSearchParams(window.location.search)
  const tabParam = urlParams.get('tab')
  if (tabParam === 'bank') {
    activeTab.value = 'bank'
  }
})

// 辅助科目验证相关
const bankVerified = ref(false)
const bankVerificationDialog = ref({
  visible: false,
  form: {
    code: ''
  },
  countdown: 0
})

const bankVerificationFormRef = ref()

// 自动加密相关
const autoEncryptTimer = ref<number | null>(null)
const encryptCountdown = ref(0) // 倒计时显示（秒）

// 当前登录用户信息（模拟）
const currentUser = ref({
  id: 'E001',
  name: '张三',
  countryCode: '+86',
  mobile: '13800138000',
  role: ['管理员'],
  hasBankPermission: true
})

const bankVerificationRules = {
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

// 站点相关
const activeSiteTab = ref('all')

// 站点列表
const siteList = ref([
  {
    label: '煤炉',
    value: 'mercari',
    enabled: true,
    description: '日本二手交易平台',
    url: 'https://mercari.com'
  },
  {
    label: '雅虎日拍',
    value: 'yahoo_auction',
    enabled: true,
    description: '日本雅虎拍卖平台',
    url: 'https://auctions.yahoo.co.jp'
  },
  {
    label: '雅虎闲置',
    value: 'yahoo_flea',
    enabled: true,
    description: '日本雅虎闲置市场',
    url: 'https://paypayfleamarket.yahoo.co.jp'
  },
  {
    label: '煤炉闲置',
    value: 'mercari_flea',
    enabled: true,
    description: '煤炉闲置市场',
    url: 'https://mercari.com'
  },
  {
    label: '亚马逊日本',
    value: 'amazon_jp',
    enabled: true,
    description: '亚马逊日本站点',
    url: 'https://amazon.co.jp'
  },
  {
    label: '乐天市场',
    value: 'rakuten',
    enabled: true,
    description: '日本乐天购物平台',
    url: 'https://rakuten.co.jp'
  },
  // 新增站点
  { label: 'Sofmap', value: 'sofmap', enabled: true, description: 'Sofmap 日本电器商城', url: 'https://www.sofmap.com' },
  { label: 'SKiT', value: 'skit', enabled: true, description: 'SKiT 官方商城', url: 'https://skit.ne.jp' },
  { label: 'Skitdolce', value: 'skitdolce', enabled: true, description: 'Skitdolce 官方', url: 'https://skitdolce.jp' },
  { label: 'Tohoanima', value: 'tohoanima', enabled: true, description: 'Tohoanima 官方', url: 'https://toho-anime.com' },
  { label: 'Kotobukiya', value: 'kotobukiya', enabled: true, description: 'Kotobukiya 官方', url: 'https://www.kotobukiya.co.jp' },
  { label: 'JUMP SHO！', value: 'jumpsho', enabled: true, description: 'JUMP SHO！', url: 'https://jumpshop-online.com' },
  { label: 'CCO', value: 'cco', enabled: true, description: 'CCO 官方', url: 'https://cco.com' },
  { label: 'Store', value: 'store', enabled: true, description: 'Store 官方', url: 'https://store.com' },
  { label: 'ANIPLEX+', value: 'aniplexplus', enabled: true, description: 'ANIPLEX+ 官方', url: 'https://www.aniplexplus.com' },
  { label: 'm78', value: 'm78', enabled: true, description: 'm78 官方', url: 'https://m-78.jp' },
  { label: 'Eeo', value: 'eeo', enabled: true, description: 'Eeo 官方', url: 'https://eeo.today' },
  { label: 'Aniplexplus', value: 'aniplexplus2', enabled: true, description: 'Aniplexplus 官方', url: 'https://aniplexplus.jp' },
  { label: 'Jumpcs', value: 'jumpcs', enabled: true, description: 'Jumpcs 官方', url: 'https://jumpcs.com' },
  { label: 'ANIME', value: 'anime', enabled: true, description: 'ANIME 官方', url: 'https://anime.com' },
  { label: 'AMNIBUS', value: 'amnibus', enabled: true, description: 'AMNIBUS 官方', url: 'https://amnibus.com' },
  { label: 'Kjoanishop！', value: 'kyoanishop', enabled: true, description: 'Kyoanishop 官方', url: 'https://kyoanishop.com' },
  { label: 'mOvIC', value: 'movic', enabled: true, description: 'Movic 官方', url: 'https://www.movic.jp' },
  { label: 'AnimeCollection', value: 'animecollection', enabled: true, description: 'AnimeCollection 官方', url: 'https://anime-collection.jp' },
  { label: 'Chara-Ani', value: 'chara_ani', enabled: true, description: 'Chara-Ani 官方', url: 'https://www.chara-ani.com' },
  { label: 'Amnibus', value: 'amnibus2', enabled: true, description: 'Amnibus 官方', url: 'https://amnibus.jp' },
  { label: 'Kyoanishop', value: 'kyoanishop2', enabled: true, description: 'Kyoanishop 官方', url: 'https://kyoanishop.jp' },
  { label: 'Movic', value: 'movic2', enabled: true, description: 'Movic 官方', url: 'https://movic.jp' }
])

// 所有启用的站点
const allSites = computed(() => {
  return siteList.value.filter(site => site.enabled)
})

// 用户管理
const userIdInput = ref('')
const quickSelectUsers = ref([
  { id: 'user001', nickname: '张三' },
  { id: 'user002', nickname: '李四' },
  { id: 'user003', nickname: '王五' },
  { id: 'admin', nickname: '管理员' }
])

// 用户数据库（模拟）- 实际应该从后端API获取
const userDatabase = ref([
  { id: 'user001', nickname: '张三', email: 'zhangsan@example.com' },
  { id: 'user002', nickname: '李四', email: 'lisi@example.com' },
  { id: 'user003', nickname: '王五', email: 'wangwu@example.com' },
  { id: 'user004', nickname: '赵六', email: 'zhaoliu@example.com' },
  { id: 'user005', nickname: '钱七', email: 'qianqi@example.com' },
  { id: 'admin', nickname: '管理员', email: 'admin@example.com' },
  { id: 'test001', nickname: '测试用户1', email: 'test1@example.com' },
  { id: 'test002', nickname: '测试用户2', email: 'test2@example.com' }
])

// 新增/编辑弹窗绑定用户批量输入与标签处理
const userIdBatchInput = ref('')
function handleBatchUserInput() {
  const ids = userIdBatchInput.value
    .split(/[,\s\n]+/)
    .map(id => id.trim())
    .filter(Boolean)
    .filter(id => !tradeDialog.value.form.bindUsers.some(u => u.id === id))
  ids.forEach(id => {
    const userInfo = userDatabase.value.find(u => u.id === id)
    tradeDialog.value.form.bindUsers.push({
      id,
      nickname: userInfo?.nickname
    })
  })
  userIdBatchInput.value = ''
}
function removeUser(userId: string) {
  const index = tradeDialog.value.form.bindUsers.findIndex(user => user.id === userId)
  if (index > -1) {
    tradeDialog.value.form.bindUsers.splice(index, 1)
    ElMessage.success('已移除用户')
  }
}

// 可用服务器列表
const availableServers = ref([
  { label: '爬虫服务器A - 192.168.1.10', value: 'server_a_192.168.1.10' },
  { label: '爬虫服务器B - 192.168.1.11', value: 'server_b_192.168.1.11' },
  { label: '爬虫服务器C - 192.168.1.12', value: 'server_c_192.168.1.12' },
  { label: '备用服务器 - 192.168.1.20', value: 'backup_192.168.1.20' }
])

// 获取启用的辅助科目列表
const enabledBankAccounts = computed(() => {
  return bankAccounts.value.filter(account => account.status === '启用')
})

// 交易账号
const tradeSearchForm = ref({
  account: '',
  payAccount: '',
  site: '',
  user: '',
  server: '',
  status: '',
  accountNickname: '',
  phone: ''
})

// 控制是否显示禁用账号
const showDisabledAccounts = ref(false)


const filteredTradeAccounts = computed(() => {
  let filtered = tradeAccounts.value

  // 按站点过滤
  if (activeSiteTab.value !== 'all') {
    filtered = filtered.filter(row => row.site === activeSiteTab.value)
  }

  // 默认只显示启用账号，除非用户主动点击显示禁用账号
  if (!showDisabledAccounts.value) {
    filtered = filtered.filter(row => row.status === '启用')
  }

  // 多条件筛选
  if (tradeSearchForm.value.account) {
    filtered = filtered.filter(row => row.account.includes(tradeSearchForm.value.account))
  }
  if (tradeSearchForm.value.payAccount) {
    filtered = filtered.filter(row => row.payAccount.includes(tradeSearchForm.value.payAccount))
  }
  if (tradeSearchForm.value.site) {
    filtered = filtered.filter(row => row.site === tradeSearchForm.value.site)
  }
  if (tradeSearchForm.value.user) {
    filtered = filtered.filter(row =>
      row.bindUsers && row.bindUsers.some((user: any) =>
        user.id.includes(tradeSearchForm.value.user) ||
        (user.nickname && user.nickname.includes(tradeSearchForm.value.user))
      )
    )
  }
  if (tradeSearchForm.value.server) {
    filtered = filtered.filter(row =>
      (row.bindServer && row.bindServer.includes(tradeSearchForm.value.server))
    )
  }
  if (tradeSearchForm.value.status) {
    filtered = filtered.filter(row => row.status === tradeSearchForm.value.status)
  }
  if (tradeSearchForm.value.accountNickname) {
    filtered = filtered.filter(row => 
      row.accountNickname && row.accountNickname.includes(tradeSearchForm.value.accountNickname)
    )
  }
  if (tradeSearchForm.value.phone) {
    filtered = filtered.filter(row => 
      row.phone && row.phone.includes(tradeSearchForm.value.phone)
    )
  }
  return filtered
})

function handleTradeSearch() {
  // 只需触发computed刷新即可
}
function resetTradeSearch() {
  tradeSearchForm.value = {
    account: '',
    payAccount: '',
    site: '',
    user: '',
    server: '',
    status: '',
    accountNickname: '',
    phone: ''
  }
}



function toggleDisabledAccounts() {
  showDisabledAccounts.value = !showDisabledAccounts.value
}


// 交易账号对话框
const tradeDialog = ref({
  visible: false,
  mode: 'add',
  form: {
    id: '',
    site: '',
    account: '',
    password: '',
    payAccounts: [] as Array<{cardNo: string, abbreviatedSubjectName?: string, subjectName?: string}>,
    accountNickname: '',
    phone: '',
    bindUsers: [] as Array<{id: string, nickname?: string}>,
    bindServer: '',
    remark: ''
  },
  editIndex: -1
})

// 生成交易账号ID
function generateTradeAccountId(): string {
  const existingIds = tradeAccounts.value.map(acc => acc.id)
  let newId = 'TA001'
  let counter = 1
  
  while (existingIds.includes(newId)) {
    counter++
    newId = `TA${counter.toString().padStart(3, '0')}`
  }
  
  return newId
}

function openTradeDialog(mode: 'add' | 'edit', row?: any, idx?: number) {
  tradeDialog.value.mode = mode
  if (mode === 'add') {
    tradeDialog.value.form = {
      id: generateTradeAccountId(),
      site: activeSiteTab.value !== 'all' ? activeSiteTab.value : '',
      account: '',
      password: '',
      payAccounts: [{ cardNo: '', abbreviatedSubjectName: '', subjectName: '' }],
      accountNickname: '',
      phone: '',
      bindUsers: [],
      bindServer: '',
      remark: ''
    }
    tradeDialog.value.editIndex = -1
  } else if (row && typeof idx === 'number') {
    // 处理编辑模式，将原有的payAccount转换为payAccounts数组
    const payAccounts = row.payAccount ? [{ cardNo: row.payAccount, abbreviatedSubjectName: '', subjectName: '' }] : [{ cardNo: '', abbreviatedSubjectName: '', subjectName: '' }]
    tradeDialog.value.form = {
      ...row,
      payAccounts: payAccounts,
      bindUsers: row.bindUsers ? [...row.bindUsers] : []
    }
    tradeDialog.value.editIndex = idx
  }
  // 清空用户ID输入框
  userIdBatchInput.value = ''
  // 重置所有密码显示状态
  resetAllPasswordVisibility()
  tradeDialog.value.visible = true
}

function saveTrade() {
  const idx = tradeDialog.value.editIndex
  
  // 验证必填字段
  if (!tradeDialog.value.form.account) {
    ElMessage.error('请输入交易账号')
    return
  }
  if (!tradeDialog.value.form.password) {
    ElMessage.error('请输入密码')
    return
  }
  if (!tradeDialog.value.form.site) {
    ElMessage.error('请选择绑定站点')
    return
  }
  if (!tradeDialog.value.form.accountNickname) {
    ElMessage.error('请输入账号昵称')
    return
  }
  if (!tradeDialog.value.form.phone) {
    ElMessage.error('请输入手机号')
    return
  }
  if (!tradeDialog.value.form.payAccounts || tradeDialog.value.form.payAccounts.length === 0 || !tradeDialog.value.form.payAccounts[0].cardNo) {
    ElMessage.error('请至少选择一个辅助科目')
    return
  }
  if (!tradeDialog.value.form.bindServer) {
    ElMessage.error('请选择绑定服务器')
    return
  }
  if (!tradeDialog.value.form.remark) {
    ElMessage.error('请输入备注信息')
    return
  }
  
  if (tradeDialog.value.mode === 'add') {
    // ID是自动生成的，理论上不会重复，但保留检查以防万一
    const existingAccount = tradeAccounts.value.find(acc => acc.id === tradeDialog.value.form.id)
    if (existingAccount) {
      ElMessage.error('交易账号ID已存在，请使用其他ID')
      return
    }
    
    // 检查交易账号是否已存在
    const existingAccountByAccount = tradeAccounts.value.find(acc => acc.account === tradeDialog.value.form.account)
    if (existingAccountByAccount) {
      ElMessage.error('交易账号已存在，请使用其他账号')
      return
    }
    
    // 新增时使用深拷贝确保响应式更新，将payAccounts转换为payAccount
    const payAccount = tradeDialog.value.form.payAccounts[0]?.cardNo || ''
    const newAccount = {
      ...tradeDialog.value.form,
      payAccount: payAccount, // 保持向后兼容
      status: '启用',
      showPassword: false
    }
    tradeAccounts.value = [newAccount, ...tradeAccounts.value]
    ElMessage.success('新增成功')
    
    // 验证业务逻辑
    validateBusinessLogic()
  } else if (idx > -1) {
    // 检查ID是否与其他账号重复（排除当前编辑的账号）
    const duplicateIdAccount = tradeAccounts.value.find((acc, index) => 
      index !== idx && acc.id === tradeDialog.value.form.id
    )
    if (duplicateIdAccount) {
      ElMessage.error('交易账号ID已存在，请使用其他ID')
      return
    }
    
    // 检查交易账号是否与其他账号重复（排除当前编辑的账号）
    const duplicateAccountAccount = tradeAccounts.value.find((acc, index) => 
      index !== idx && acc.account === tradeDialog.value.form.account
    )
    if (duplicateAccountAccount) {
      ElMessage.error('交易账号已存在，请使用其他账号')
      return
    }
    
    // 编辑时使用深拷贝确保响应式更新，将payAccounts转换为payAccount
    const payAccount = tradeDialog.value.form.payAccounts[0]?.cardNo || ''
    const updatedAccounts = tradeAccounts.value.map((acc, index) => {
      if (index === idx) {
        return {
          ...tradeDialog.value.form,
          payAccount: payAccount, // 保持向后兼容
          status: acc.status,
          showPassword: acc.showPassword
        }
      }
      return acc
    })
    tradeAccounts.value = updatedAccounts
    ElMessage.success('编辑成功')
    
    // 验证业务逻辑
    validateBusinessLogic()
  }
  // 重置所有密码显示状态
  resetAllPasswordVisibility()
  tradeDialog.value.visible = false
}

function toggleTradeStatus(row: any) {
  if (row.status === '启用') {
    // 如果要禁用，检查是否有绑定用户
    if (row.bindUsers && row.bindUsers.length > 0) {
      // 有绑定用户，需要先转移用户
      userTransferDialog.value.currentAccount = row.account
      userTransferDialog.value.currentUsers = row.bindUsers
      userTransferDialog.value.targetRow = row
      userTransferDialog.value.visible = true
    } else {
      // 没有绑定用户，直接禁用
      const updatedAccounts = tradeAccounts.value.map(acc => {
        if (acc.account === row.account) {
          return { ...acc, status: '禁用' }
        }
        return acc
      })
      tradeAccounts.value = updatedAccounts
      ElMessage.success('已禁用')
      
      // 验证业务逻辑
      validateBusinessLogic()
    }
  } else {
    // 启用账号
    const updatedAccounts = tradeAccounts.value.map(acc => {
      if (acc.account === row.account) {
        return { ...acc, status: '启用' }
      }
      return acc
    })
    tradeAccounts.value = updatedAccounts
    ElMessage.success('已启用')
    
    // 验证业务逻辑
    validateBusinessLogic()
  }
}

// 重置所有密码显示状态
function resetAllPasswordVisibility() {
  const updatedAccounts = tradeAccounts.value.map(acc => ({
    ...acc,
    showPassword: false
  }))
  tradeAccounts.value = updatedAccounts
}

// 密码显示/隐藏 - 同一时间只能查看一个密码
function togglePasswordVisibility(row: any) {
  const updatedAccounts = tradeAccounts.value.map(acc => {
    if (acc.account === row.account) {
      // 切换当前行的密码显示状态
      return { ...acc, showPassword: !acc.showPassword }
    } else {
      // 关闭其他所有行的密码显示
      return { ...acc, showPassword: false }
    }
  })
  tradeAccounts.value = updatedAccounts
}

// 验证业务逻辑：禁用的账号不应该有绑定用户
function validateBusinessLogic() {
  const invalidAccounts = tradeAccounts.value.filter(acc => 
    acc.status === '禁用' && acc.bindUsers && acc.bindUsers.length > 0
  )
  
  if (invalidAccounts.length > 0) {
    console.warn('发现业务逻辑错误：以下禁用的账号仍有绑定用户：', 
      invalidAccounts.map(acc => acc.account))
  }
}

// 辅助科目脱敏处理：只显示后四位数字
function maskPayAccount(payAccount: string): string {
  if (!payAccount || payAccount.length < 4) {
    return payAccount || ''
  }
  
  const lastFour = payAccount.slice(-4)
  const maskedPart = '*'.repeat(payAccount.length - 4)
  return maskedPart + lastFour
}

// 根据辅助科目获取银行信息
function getBankInfoByPayAccount(payAccount: string): { bankName: string; subjectName: string } | null {
  const bankAccount = bankAccounts.value.find(acc => acc.cardNo === payAccount)
  if (bankAccount) {
    return {
      bankName: bankAccount.formalSubjectName,
      subjectName: bankAccount.subjectName
    }
  }
  return null
}

// 获取格式化的辅助科目显示文本
function getFormattedAuxiliarySubject(payAccount: string): string {
  if (!payAccount) return '未设置'
  
  const bankAccount = bankAccounts.value.find(acc => acc.cardNo === payAccount)
  if (bankAccount) {
    return `${bankAccount.abbreviatedSubjectName} - ${bankAccount.subjectName} - ${maskPayAccount(bankAccount.cardNo)}`
  }
  
  return maskPayAccount(payAccount)
}

// 获取辅助科目绑定的站点信息（从交易账号页面回显）
function getBankBoundSites(bankAccount: any) {
  const boundSites: any[] = []
  
  // 从交易账号中查找使用该辅助科目的账号
  tradeAccounts.value.forEach(tradeAccount => {
    if (tradeAccount.payAccount === bankAccount.cardNo) {
      boundSites.push({
        site: tradeAccount.site,
        tradeAccount: tradeAccount.account
      })
    }
  })
  
  return boundSites
}

// 用户管理功能
function addUserById() {
  const userId = userIdInput.value.trim()
  if (!userId) {
    ElMessage.warning('请输入用户ID')
    return
  }

  // 检查是否已经添加过
  if (tradeDialog.value.form.bindUsers.some(user => user.id === userId)) {
    ElMessage.warning('该用户已经添加过了')
    userIdInput.value = ''
    return
  }

  // 从用户数据库中查找用户信息
  const userInfo = userDatabase.value.find(user => user.id === userId)

  if (userInfo) {
    // 找到用户，添加完整信息
    tradeDialog.value.form.bindUsers.push({
      id: userInfo.id,
      nickname: userInfo.nickname
    })
    ElMessage.success(`成功添加用户：${userInfo.nickname}`)
  } else {
    // 未找到用户，只添加ID
    tradeDialog.value.form.bindUsers.push({
      id: userId,
      nickname: undefined
    })
    ElMessage.warning(`用户ID "${userId}" 不存在于系统中，已添加但无法显示昵称`)
  }

  userIdInput.value = ''
}

function addQuickUser(user: any) {
  // 检查是否已经添加过
  if (tradeDialog.value.form.bindUsers.some(u => u.id === user.id)) {
    ElMessage.warning('该用户已经添加过了')
    return
  }

  tradeDialog.value.form.bindUsers.push({
    id: user.id,
    nickname: user.nickname
  })
  ElMessage.success(`成功添加用户：${user.nickname}`)
}

// 添加辅助科目
function addPayAccount() {
  tradeDialog.value.form.payAccounts.push({
    cardNo: '',
    abbreviatedSubjectName: '',
    subjectName: ''
  })
}

// 删除辅助科目
function removePayAccount(index: number) {
  tradeDialog.value.form.payAccounts.splice(index, 1)
}

// 跳转到站点管理页面
const router = useRouter()
function goToSiteManage() {
  router.push('/settings/site')
}

// 页面加载时自动切换tab（支持从站点管理跳转）
onMounted(() => {
  const tab = window.localStorage.getItem('accountManageActiveSiteTab')
  if (tab) {
    activeSiteTab.value = tab
    window.localStorage.removeItem('accountManageActiveSiteTab')
  }
  
  // 验证业务逻辑
  validateBusinessLogic()
})

// 站点管理
const siteFormRef = ref()
const siteDialog = ref({
  visible: false,
  mode: 'add',
  form: {
    label: '',
    value: '',
    description: '',
    url: '',
    enabled: true
  },
  editIndex: -1
})

// 表单验证规则
const siteFormRules = {
  label: [
    { required: true, message: '请输入站点名称', trigger: 'blur' },
    { min: 2, max: 20, message: '站点名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '请输入站点标识', trigger: 'blur' },
    { min: 2, max: 30, message: '站点标识长度在 2 到 30 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '站点标识只能包含英文、数字和下划线', trigger: 'blur' },
    { validator: validateSiteValue, trigger: 'blur' }
  ]
}

// 验证站点标识唯一性
function validateSiteValue(_rule: any, value: string, callback: any) {
  if (!value) {
    callback()
    return
  }

  // 检查是否与其他站点冲突（编辑时排除自己）
  const currentIndex = siteDialog.value.editIndex
  const exists = siteList.value.some((site: any, index: number) =>
    site.value === value && (siteDialog.value.mode === 'add' || index !== currentIndex)
  )
  if (exists) {
    callback(new Error('站点标识已存在'))
    return
  }

  callback()
}

function openSiteDialog(mode: 'add' | 'edit', row?: any, idx?: number) {
  siteDialog.value.mode = mode
  if (mode === 'add') {
    siteDialog.value.form = {
      label: '',
      value: '',
      description: '',
      url: '',
      enabled: true
    }
    siteDialog.value.editIndex = -1
  } else if (row && typeof idx === 'number') {
    siteDialog.value.form = { ...row }
    siteDialog.value.editIndex = idx
  }
  siteDialog.value.visible = true

  // 清除表单验证
  setTimeout(() => {
    siteFormRef.value?.clearValidate()
  }, 100)
}

function saveSite() {
  siteFormRef.value?.validate((valid: boolean) => {
    if (!valid) {
      return
    }

    const idx = siteDialog.value.editIndex
    if (siteDialog.value.mode === 'add') {
      siteList.value.push({
        ...siteDialog.value.form
      })
      ElMessage.success('新增站点成功')
    } else if (idx > -1) {
      // 更新站点信息
      siteList.value[idx] = {
        ...siteDialog.value.form
      }
      ElMessage.success('编辑站点成功')
    }
    siteDialog.value.visible = false
  })
}

function deleteSite(_index: number, row: any) {
  // 检查是否有关联账号
  const accountCount = getAccountCountBySite(row.value)
  if (accountCount > 0) {
    ElMessage.warning(`该站点有 ${accountCount} 个关联账号，无法删除`)
    return
  }

  ElMessageBox.confirm(`确定要删除站点"${row.label}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 从站点列表中删除
    const siteIndex = siteList.value.findIndex((site: any) => site.value === row.value)
    if (siteIndex > -1) {
      siteList.value.splice(siteIndex, 1)
      ElMessage.success('删除成功')

      // 如果当前选中的是被删除的站点，切换到"全部"
      if (activeSiteTab.value === row.value) {
        activeSiteTab.value = 'all'
      }
    }
  })
}

// 获取站点关联的账号数量
function getAccountCountBySite(siteValue: string) {
  return tradeAccounts.value.filter(account => account.site === siteValue).length
}



// 切换站点状态
function toggleSiteStatus(site: any) {
  const status = site.enabled ? '启用' : '禁用'
  ElMessage.success(`站点已${status}`)

  // 如果禁用的是当前选中的站点，切换到"全部"
  if (!site.enabled && activeSiteTab.value === site.value) {
    activeSiteTab.value = 'all'
  }
}

// 获取站点显示名称
function getSiteDisplayName(siteValue: string): string {
  const site = siteList.value.find(s => s.value === siteValue)
  return site ? site.label : siteValue
}

// 获取站点标签类型
function getSiteTagType(siteValue: string): string {
  const site = siteList.value.find(s => s.value === siteValue)
  if (!site) return 'info'
  
  // 根据站点类型返回不同的标签颜色
  const siteTypeMap: { [key: string]: string } = {
    'mercari': 'primary',
    'yahoo_auction': 'success',
    'yahoo_flea': 'warning',
    'mercari_flea': 'danger',
    'amazon': 'info',
    'rakuten': 'success'
  }
  
  return siteTypeMap[siteValue] || 'info'
}



// 服务器切换
const serverSwitchDialog = ref({
  visible: false,
  currentAccount: '',
  currentServer: '',
  newServer: '',
  targetRow: null as any
})

// 交易账号切换
const tradeAccountSwitchDialog = ref({
  visible: false,
  currentAccount: '',
  currentUsers: [] as any[],
  newAccount: '',
  targetRow: null as any
})

// 用户转移对话框
const userTransferDialog = ref({
  visible: false,
  currentAccount: '',
  currentUsers: [] as any[],
  targetAccount: '',
  targetRow: null as any
})

function switchServer(row: any) {
  serverSwitchDialog.value.currentAccount = row.account
  serverSwitchDialog.value.currentServer = row.bindServer
  serverSwitchDialog.value.newServer = ''
  serverSwitchDialog.value.targetRow = row
  serverSwitchDialog.value.visible = true
}

function switchTradeAccount(row: any) {
  tradeAccountSwitchDialog.value.currentAccount = row.account
  tradeAccountSwitchDialog.value.currentUsers = row.bindUsers
  tradeAccountSwitchDialog.value.newAccount = ''
  tradeAccountSwitchDialog.value.targetRow = row
  tradeAccountSwitchDialog.value.visible = true
}

function confirmSwitchServer() {
  if (serverSwitchDialog.value.targetRow && serverSwitchDialog.value.newServer) {
    serverSwitchDialog.value.targetRow.bindServer = serverSwitchDialog.value.newServer
    ElMessage.success('服务器切换成功')
    serverSwitchDialog.value.visible = false
  } else {
    ElMessage.warning('请选择新服务器')
  }
}

function confirmSwitchTradeAccount() {
  if (tradeAccountSwitchDialog.value.targetRow && tradeAccountSwitchDialog.value.newAccount) {
    // 找到目标交易账号
    const targetAccount = tradeAccounts.value.find(acc => acc.account === tradeAccountSwitchDialog.value.newAccount)
    if (!targetAccount) {
      ElMessage.error('目标交易账号不存在')
      return
    }
    
    // 保存当前绑定用户
    const currentUsers = [...tradeAccountSwitchDialog.value.currentUsers]
    
    // 使用深拷贝更新数据，确保响应式更新
    const updatedAccounts = tradeAccounts.value.map(acc => {
      if (acc.account === tradeAccountSwitchDialog.value.targetRow.account) {
        return {
          ...acc,
          account: targetAccount.account,
          password: targetAccount.password,
          payAccount: targetAccount.payAccount,
          bindServer: targetAccount.bindServer,
          site: targetAccount.site,
          remark: targetAccount.remark,
          bindUsers: currentUsers
        }
      }
      return acc
    })
    tradeAccounts.value = updatedAccounts
    
    ElMessage.success(`成功将交易账号更换为 ${tradeAccountSwitchDialog.value.newAccount}，绑定用户保持不变`)
    tradeAccountSwitchDialog.value.visible = false
  } else {
    ElMessage.warning('请选择目标交易账号')
  }
}

function confirmUserTransfer() {
  if (userTransferDialog.value.targetRow && userTransferDialog.value.targetAccount) {
    // 找到目标交易账号
    const targetAccount = tradeAccounts.value.find(acc => acc.account === userTransferDialog.value.targetAccount)
    if (!targetAccount) {
      ElMessage.error('目标交易账号不存在')
      return
    }
    
    // 将绑定用户转移到目标账号
    const currentUsers = [...userTransferDialog.value.currentUsers]
    
    // 确保目标账号的bindUsers是数组
    if (!targetAccount.bindUsers) {
      targetAccount.bindUsers = []
    }
    
    // 检查重复用户，避免重复添加
    const existingUserIds = new Set(targetAccount.bindUsers.map((user: any) => user.id))
    const newUsers = currentUsers.filter((user: any) => !existingUserIds.has(user.id))
    
    // 使用深拷贝确保响应式更新
    const updatedAccounts = tradeAccounts.value.map(acc => {
      if (acc.account === userTransferDialog.value.targetRow.account) {
        return { ...acc, bindUsers: [], status: '禁用' }
      } else if (acc.account === userTransferDialog.value.targetAccount) {
        return { ...acc, bindUsers: [...(acc.bindUsers || []), ...newUsers] }
      }
      return acc
    })
    tradeAccounts.value = updatedAccounts
    
    // 显示转移结果信息
    const transferredCount = newUsers.length
    const duplicateCount = currentUsers.length - newUsers.length
    let message = `成功将 ${transferredCount} 个用户转移到交易账号 ${userTransferDialog.value.targetAccount}，当前账号已禁用`
    if (duplicateCount > 0) {
      message += `（过滤了 ${duplicateCount} 个重复用户）`
    }
    
    // 如果详情对话框正在显示，且显示的是被转移的账号，则关闭详情对话框
    if (tradeDetailDialog.value.visible && tradeDetailDialog.value.data && 
        tradeDetailDialog.value.data.account === userTransferDialog.value.currentAccount) {
      tradeDetailDialog.value.visible = false
    }
    
    // 清空对话框数据
    userTransferDialog.value.currentUsers = []
    userTransferDialog.value.targetAccount = ''
    userTransferDialog.value.targetRow = null
    
    ElMessage.success(message)
    userTransferDialog.value.visible = false
    
    // 验证业务逻辑
    validateBusinessLogic()
    

  } else {
    ElMessage.warning('请选择目标交易账号')
  }
}
// 批量导入
// const tradeImportDialog = ref(false)
// const tradeImportText = ref('')
// function doTradeImport() {
//   const lines = tradeImportText.value.split('\n').map(l => l.trim()).filter(Boolean)
//   for (const line of lines) {
//     const [site, account, password, payAccount] = line.split(',')
//     if (site && account && password && payAccount) {
//       tradeAccounts.value.unshift({ site, account, password, payAccount, status: '启用' })
//     }
//   }
//   tradeImportDialog.value = false
//   tradeImportText.value = ''
// }
function downloadTradeTemplate() {
  // 生成Excel模板
  const ws = XLSX.utils.aoa_to_sheet([
            ['站点', '交易账号', '密码', '辅助科目', '绑定用户ID(多个用逗号分隔)', '绑定服务器', '备注'],
    ['mercari', 'mercari_user1', 'password123', '1234567890', 'user001,user002', '爬虫服务器A - 192.168.1.10', '主要采集账号'],
    ['yahoo_auction', 'yahoo_user1', 'password456', '9876543210', 'user003', '爬虫服务器B - 192.168.1.11', '备用账号'],
    ['yahoo_flea', 'yahoo_flea_user', 'password789', '5555666677', '', '', '测试账号']
  ])
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '交易账号模板')
  XLSX.writeFile(wb, '交易账号导入模板.xlsx')
}
function beforeTradeExcelUpload(file: File) {
  const reader = new FileReader()
  reader.onload = (e: any) => {
    const data = new Uint8Array(e.target.result)
    const workbook = XLSX.read(data, { type: 'array' })
    const sheet = workbook.Sheets[workbook.SheetNames[0]]
    const rows = XLSX.utils.sheet_to_json(sheet, { header: 1 })

    // rows[0]为表头
    let importCount = 0
    for (let i = 1; i < rows.length; i++) {
      const row = rows[i] as any[]
      if (row.length < 3) continue // 至少需要站点、账号、密码

      const [site, account, password, payAccount, bindUserIds, bindServer, remark] = row

      if (site && account && password) {
        // 解析绑定用户ID
        const bindUsers: Array<{id: string, nickname?: string}> = []
        if (bindUserIds && typeof bindUserIds === 'string') {
          const userIds = bindUserIds.split(',').map((id: string) => id.trim()).filter(Boolean)
          for (const userId of userIds) {
            const userInfo = userDatabase.value.find(user => user.id === userId)
            bindUsers.push({
              id: userId,
              nickname: userInfo?.nickname
            })
          }
        }

        tradeAccounts.value.unshift({
          site,
          account,
          password,
          payAccount: payAccount || '',
          bindUsers,
          bindServer: bindServer || '',
          remark: remark || '',
          status: '启用',
          showPassword: false
        })
        importCount++
      }
    }

    ElMessage.success(`成功导入${importCount}条交易账号数据`)
  }
  reader.readAsArrayBuffer(file)
  // 阻止默认上传
  return false
}
// 会计科目 - 严格按照用户表格内容
const bankAccounts = ref([
  { 
    id: '1',
    formalSubjectId: '0', 
    formalSubjectName: '諸口(汇总)', 
    abbreviatedSubjectName: '諸口(汇总)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '2',
    formalSubjectId: '1', 
    formalSubjectName: '科目未決定(科目未定)', 
    abbreviatedSubjectName: '科目未決(科目未定)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '3',
    formalSubjectId: '111', 
    formalSubjectName: '現金(现金)', 
    abbreviatedSubjectName: '現金(现金)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '4',
    formalSubjectId: '112', 
    formalSubjectName: '小口現金(零用现金)', 
    abbreviatedSubjectName: '小口現金(零用现金)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '5',
    formalSubjectId: '113', 
    formalSubjectName: 'ヤフーウォレット(雅虎钱包)', 
    abbreviatedSubjectName: 'ヤフーウ(雅虎钱包)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '6',
    formalSubjectId: '114', 
    formalSubjectName: 'Pay P (PayPay)', 
    abbreviatedSubjectName: 'Pay P (PayPay)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '7',
    formalSubjectId: '121', 
    formalSubjectName: '当座預金(活期存款)', 
    abbreviatedSubjectName: '当座預金(活期存款)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '8',
    formalSubjectId: '122', 
    formalSubjectName: '', 
    abbreviatedSubjectName: '当座1(活期1)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '9',
    formalSubjectId: '123', 
    formalSubjectName: '', 
    abbreviatedSubjectName: '当座2(活期2)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '10',
    formalSubjectId: '124', 
    formalSubjectName: '', 
    abbreviatedSubjectName: '当座3(活期3)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '11',
    formalSubjectId: '131', 
    formalSubjectName: '京葉銀行蘇我支店(京叶银行苏我支行)', 
    abbreviatedSubjectName: '京葉銀行(京叶银行)',
    subjectId: '1', 
    subjectName: 'UFJ0805861', 
    cardNo: '6222021234567890', 
    safeCode: '123', 
    expiryDate: '12/25',
    status: '启用'
  },
  { 
    id: '12',
    formalSubjectId: '132', 
    formalSubjectName: '三菱東京UFJ(三菱东京UFJ)', 
    abbreviatedSubjectName: '三菱東京(三菱东京)',
    subjectId: '1', 
    subjectName: 'UFJ0805861', 
    cardNo: '6222021234567891', 
    safeCode: '456', 
    expiryDate: '06/26',
    status: '启用'
  },
  { 
    id: '13',
    formalSubjectId: '132', 
    formalSubjectName: '三菱東京UFJ(三菱东京UFJ)', 
    abbreviatedSubjectName: '三菱東京(三菱东京)',
    subjectId: '2', 
    subjectName: 'UFJ1661590', 
    cardNo: '6222021234567892', 
    safeCode: '789', 
    expiryDate: '09/24',
    status: '启用'
  },
  { 
    id: '14',
    formalSubjectId: '132', 
    formalSubjectName: '三菱東京UFJ(三菱东京UFJ)', 
    abbreviatedSubjectName: '三菱東京(三菱东京)',
    subjectId: '3', 
    subjectName: 'UFJ2204624', 
    cardNo: '6222021234567893', 
    safeCode: '321', 
    expiryDate: '03/27',
    status: '启用'
  },
  { 
    id: '15',
    formalSubjectId: '132', 
    formalSubjectName: '三菱東京UFJ(三菱东京UFJ)', 
    abbreviatedSubjectName: '三菱東京(三菱东京)',
    subjectId: '4', 
    subjectName: 'UFJ2420324', 
    cardNo: '6222021234567894', 
    safeCode: '654', 
    expiryDate: '07/28',
    status: '启用'
  },
  { 
    id: '16',
    formalSubjectId: '132', 
    formalSubjectName: '三菱東京UFJ(三菱东京UFJ)', 
    abbreviatedSubjectName: '三菱東京(三菱东京)',
    subjectId: '5', 
    subjectName: 'UFJ2420133', 
    cardNo: '6222021234567895', 
    safeCode: '987', 
    expiryDate: '11/29',
    status: '启用'
  },
  { 
    id: '17',
    formalSubjectId: '133', 
    formalSubjectName: 'ゆうちょ銀行(邮储银行)', 
    abbreviatedSubjectName: 'ゆうちょ(邮储银行)',
    subjectId: '1', 
    subjectName: 'ゆうちょ普通6100949(邮储普通6100949)', 
    cardNo: '6222021234567896', 
    safeCode: '147', 
    expiryDate: '05/30',
    status: '启用'
  },
  { 
    id: '18',
    formalSubjectId: '134', 
    formalSubjectName: 'ゆうちょ銀行法人(邮储银行法人)', 
    abbreviatedSubjectName: 'ゆうちょ(邮储银行)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '19',
    formalSubjectId: '135', 
    formalSubjectName: '三菱東京UFJ(三菱东京UFJ)', 
    abbreviatedSubjectName: '三菱東京(三菱东京)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '20',
    formalSubjectId: '136', 
    formalSubjectName: 'ジャパンネット銀行(日本网络银行)', 
    abbreviatedSubjectName: 'ジャパン(日本)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '21',
    formalSubjectId: '137', 
    formalSubjectName: '三井住友銀行(三井住友银行)', 
    abbreviatedSubjectName: '三井住友(三井住友)',
    subjectId: '1', 
    subjectName: '三井住友普通8367646(三井住友普通8367646)', 
    cardNo: '6222021234567897', 
    safeCode: '258', 
    expiryDate: '08/31',
    status: '启用'
  },
  { 
    id: '22',
    formalSubjectId: '137', 
    formalSubjectName: '三井住友銀行(三井住友银行)', 
    abbreviatedSubjectName: '三井住友(三井住友)',
    subjectId: '2', 
    subjectName: '三井住友普通8506201(三井住友普通8506201)', 
    cardNo: '6222021234567898', 
    safeCode: '369', 
    expiryDate: '12/32',
    status: '启用'
  },
  { 
    id: '23',
    formalSubjectId: '141', 
    formalSubjectName: '定期預金(定期存款)', 
    abbreviatedSubjectName: '定期預金(定期存款)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '24',
    formalSubjectId: '142', 
    formalSubjectName: '積立預金(储蓄存款)', 
    abbreviatedSubjectName: '積立預金(储蓄存款)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '25',
    formalSubjectId: '144', 
    formalSubjectName: '', 
    abbreviatedSubjectName: '固預金2(固定存款2)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '26',
    formalSubjectId: '151', 
    formalSubjectName: '受取手形(应收票据)', 
    abbreviatedSubjectName: '受取手形(应收票据)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '27',
    formalSubjectId: '152', 
    formalSubjectName: '売掛金(应收账款)', 
    abbreviatedSubjectName: '売掛金(应收账款)',
    subjectId: '1', 
    subjectName: '7080 ?梦(7080?梦)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '28',
    formalSubjectId: '152', 
    formalSubjectName: '売掛金(应收账款)', 
    abbreviatedSubjectName: '売掛金(应收账款)',
    subjectId: '9999', 
    subjectName: 'その他(其他)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '29',
    formalSubjectId: '153', 
    formalSubjectName: '', 
    abbreviatedSubjectName: '営債権1(营业债权1)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '30',
    formalSubjectId: '154', 
    formalSubjectName: '', 
    abbreviatedSubjectName: '営債権2(营业债权2)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '31',
    formalSubjectId: '155', 
    formalSubjectName: '不渡手形(拒付票据)', 
    abbreviatedSubjectName: '不渡手形(拒付票据)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '32',
    formalSubjectId: '159', 
    formalSubjectName: '内部資金移動(内部资金转移)', 
    abbreviatedSubjectName: '内部資金(内部资金)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '33',
    formalSubjectId: '162', 
    formalSubjectName: '貸倒引当金(坏账准备金)', 
    abbreviatedSubjectName: '貸倒引当(坏账准备)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '34',
    formalSubjectId: '164', 
    formalSubjectName: '有価証券(有价证券)', 
    abbreviatedSubjectName: '有価証券(有价证券)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '35',
    formalSubjectId: '171', 
    formalSubjectName: '商品(商品)', 
    abbreviatedSubjectName: '商品(商品)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '36',
    formalSubjectId: '172', 
    formalSubjectName: '製品(产品)', 
    abbreviatedSubjectName: '製品(产品)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '37',
    formalSubjectId: '173', 
    formalSubjectName: '半製品(半成品)', 
    abbreviatedSubjectName: '半製品(半成品)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '38',
    formalSubjectId: '174', 
    formalSubjectName: '原材料(原材料)', 
    abbreviatedSubjectName: '原材料(原材料)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '39',
    formalSubjectId: '175', 
    formalSubjectName: '仕掛品(在产品)', 
    abbreviatedSubjectName: '仕掛品(在产品)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '40',
    formalSubjectId: '176', 
    formalSubjectName: '貯蔵品(库存物品)', 
    abbreviatedSubjectName: '貯蔵品(库存物品)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '41',
    formalSubjectId: '177', 
    formalSubjectName: '貯蔵品(库存物品)', 
    abbreviatedSubjectName: '貯蔵品(库存物品)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '42',
    formalSubjectId: '181', 
    formalSubjectName: '前渡金(预付款)', 
    abbreviatedSubjectName: '前渡金(预付款)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '43',
    formalSubjectId: '182', 
    formalSubjectName: '短期貸付金(短期贷款)', 
    abbreviatedSubjectName: '短期貸付(短期贷款)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '44',
    formalSubjectId: '183', 
    formalSubjectName: '仮払金(暂付款)', 
    abbreviatedSubjectName: '仮払金(暂付款)',
    subjectId: '1', 
    subjectName: '未清算(未清算)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '45',
    formalSubjectId: '183', 
    formalSubjectName: '仮払金(暂付款)', 
    abbreviatedSubjectName: '仮払金(暂付款)',
    subjectId: '2', 
    subjectName: '清算済(已清算)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '46',
    formalSubjectId: '184', 
    formalSubjectName: '前払費用(预付费用)', 
    abbreviatedSubjectName: '前払費用(预付费用)',
    subjectId: '1', 
    subjectName: '株式会社志東 事務所(株式会社志东事务所)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '47',
    formalSubjectId: '184', 
    formalSubjectName: '前払費用(预付费用)', 
    abbreviatedSubjectName: '前払費用(预付费用)',
    subjectId: '2', 
    subjectName: 'BMW523i ローン手数(BMW523i贷款手续费)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '48',
    formalSubjectId: '184', 
    formalSubjectName: '前払費用(预付费用)', 
    abbreviatedSubjectName: '前払費用(预付费用)',
    subjectId: '3', 
    subjectName: '崔勉 プレハブ倉庫地(崔勉活动板房仓库地)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '49',
    formalSubjectId: '184', 
    formalSubjectName: '前払費用(预付费用)', 
    abbreviatedSubjectName: '前払費用(预付费用)',
    subjectId: '4', 
    subjectName: 'プレハブ地代(活动板房地租)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '50',
    formalSubjectId: '184', 
    formalSubjectName: '前払費用(预付费用)', 
    abbreviatedSubjectName: '前払費用(预付费用)',
    subjectId: '5', 
    subjectName: 'フラッツ100 (Flats100)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '51',
    formalSubjectId: '184', 
    formalSubjectName: '前払費用(预付费用)', 
    abbreviatedSubjectName: '前払費用(预付费用)',
    subjectId: '9999', 
    subjectName: 'その他(其他)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '52',
    formalSubjectId: '185', 
    formalSubjectName: '未収入金(其他应收款)', 
    abbreviatedSubjectName: '未収入金(其他应收款)',
    subjectId: '1', 
    subjectName: '消費税還付未収金(消费退税应收款)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '53',
    formalSubjectId: '185', 
    formalSubjectName: '未収入金(其他应收款)', 
    abbreviatedSubjectName: '未収入金(其他应收款)',
    subjectId: '2', 
    subjectName: 'ユニヴァペイキャスト (Univa Paycast)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '54',
    formalSubjectId: '185', 
    formalSubjectName: '未収入金(其他应收款)', 
    abbreviatedSubjectName: '未収入金(其他应收款)',
    subjectId: '3', 
    subjectName: 'ニューエイジ (New Age)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '55',
    formalSubjectId: '186', 
    formalSubjectName: '立替金(垫付款)', 
    abbreviatedSubjectName: '立替金(垫付款)',
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '56',
    formalSubjectId: '187', 
    formalSubjectName: '預け金(寄存金)', 
    abbreviatedSubjectName: '預け金(寄存金)',
    subjectId: '1', 
    subjectName: 'ヤフー預金払い(雅虎存款支付)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '57',
    formalSubjectId: '187', 
    formalSubjectName: '預け金(寄存金)', 
    abbreviatedSubjectName: '預け金(寄存金)',
    subjectId: '2', 
    subjectName: 'BMW リサイクル預託 (BMW回收保证金)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  },
  { 
    id: '58',
    formalSubjectId: '187', 
    formalSubjectName: '預け金(寄存金)', 
    abbreviatedSubjectName: '預け金(寄存金)',
    subjectId: '3', 
    subjectName: 'セレナ リサイクル預(Serena回收保证金)', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  }
])
const bankSearch = ref('')
const bankStatusFilter = ref('')
const showDisabledBankAccounts = ref(false)
const filteredBankAccounts = computed(() => {
  let filtered = bankAccounts.value
  
  // 根据搜索条件过滤
  if (bankSearch.value) {
    filtered = filtered.filter(row =>
      row.cardNo.includes(bankSearch.value) ||
      row.safeCode.includes(bankSearch.value) ||
      row.formalSubjectName.includes(bankSearch.value) ||
      row.subjectName.includes(bankSearch.value)
    )
  }
  
  // 根据状态筛选过滤
  if (bankStatusFilter.value) {
    filtered = filtered.filter(row => row.status === bankStatusFilter.value)
  }
  
  // 根据显示禁用账号设置过滤（当没有选择状态筛选时）
  if (!showDisabledBankAccounts.value && !bankStatusFilter.value) {
    filtered = filtered.filter(row => row.status === '启用')
  }
  
  return filtered
})
const bankDialog = ref({ 
  visible: false, 
  mode: 'add', 
  form: { 
    id: '',
    formalSubjectId: '', 
    formalSubjectName: '', 
    abbreviatedSubjectName: '', 
    subjectId: '', 
    subjectName: '', 
    cardNo: '', 
    safeCode: '', 
    expiryDate: '',
    status: '启用'
  }, 
  editIndex: -1 
})




function openBankDialog(mode: 'add' | 'edit', row?: any, idx?: number) {
  bankDialog.value.mode = mode
  if (mode === 'add') {
    bankDialog.value.form = { 
      id: '',
      formalSubjectId: '', 
      formalSubjectName: '', 
      abbreviatedSubjectName: '', 
      subjectId: '', 
      subjectName: '', 
      cardNo: '', 
      safeCode: '', 
      expiryDate: '',
      status: '启用'
    }
    bankDialog.value.editIndex = -1
  } else if (row && typeof idx === 'number') {
    bankDialog.value.form = { ...row }
    bankDialog.value.editIndex = idx
  }
  bankDialog.value.visible = true
}



function saveBank() {
  const idx = bankDialog.value.editIndex
  if (bankDialog.value.mode === 'add') {
    bankAccounts.value.unshift({ ...bankDialog.value.form })
    ElMessage.success('新增成功')
  } else if (idx > -1) {
    bankAccounts.value[idx] = { ...bankDialog.value.form }
    ElMessage.success('编辑成功')
  }
  bankDialog.value.visible = false
}



function toggleDisabledBankAccounts() {
  showDisabledBankAccounts.value = !showDisabledBankAccounts.value
}

function toggleBankStatus(row: any) {
  row.status = row.status === '启用' ? '禁用' : '启用'
  ElMessage.success(`${row.status === '启用' ? '启用' : '禁用'}成功`)
}

function resetBankFilter() {
  bankSearch.value = ''
  bankStatusFilter.value = ''
}

// 获取辅助科目绑定站点的提示信息
function getBankSitesTooltip(sites: any[]) {
  if (!sites || sites.length === 0) return '未绑定站点'
  return sites.map(siteInfo => `${siteInfo.site} - ${siteInfo.tradeAccount}`).join('\n')
}

// 跳转到辅助科目绑定站点详情页面
function goToBankSitesDetail(row: any) {
  router.push(`/settings/bank-sites/${row.id}`)
}





// 辅助科目验证相关方法
// 监听辅助科目tab切换
watch(() => activeTab.value, (newTab) => {
  // 重置所有密码显示状态
  resetAllPasswordVisibility()
  
  if (newTab === 'bank') {
    // 检查当前用户是否有权限
    if (!currentUser.value.hasBankPermission) {
      ElMessage.error('您没有访问辅助科目的权限')
      activeTab.value = 'trade'
      return
    }
    
    // 检查sessionStorage中的验证状态和倒计时
    const storedVerified = sessionStorage.getItem('bankVerified')
    const storedCountdown = sessionStorage.getItem('bankEncryptCountdown')
    
    if (storedVerified === 'true' && storedCountdown && parseInt(storedCountdown) > 0) {
      // 如果验证状态存在且倒计时大于0，恢复状态
      bankVerified.value = true
      encryptCountdown.value = parseInt(storedCountdown)
      
      // 如果倒计时大于0且没有正在运行的定时器，启动定时器
      if (encryptCountdown.value > 0 && !autoEncryptTimer.value) {
        startAutoEncrypt()
      }
    } else if (!bankVerified.value) {
      // 如果没有验证状态或倒计时已到，显示验证弹窗
      bankVerificationDialog.value.visible = true
    }
  }
})

// 发送验证码
function sendBankVerificationCode() {
  // 模拟发送验证码
  bankVerificationDialog.value.countdown = 60
  const timer = setInterval(() => {
    bankVerificationDialog.value.countdown--
    if (bankVerificationDialog.value.countdown <= 0) {
      clearInterval(timer)
    }
  }, 1000)
  
  ElMessage.success(`验证码已发送到 ${currentUser.value.name} 的手机`)
}

// 取消验证
function cancelBankVerification() {
  bankVerificationDialog.value.visible = false
  activeTab.value = 'trade' // 切换回交易账号tab
}

// 确认验证
function confirmBankVerification() {
  bankVerificationFormRef.value?.validate((valid: boolean) => {
    if (!valid) return
    
    // 模拟验证码验证（实际应该调用后端API）
    if (bankVerificationDialog.value.form.code === '123456') {
      bankVerified.value = true
      bankVerificationDialog.value.visible = false
      ElMessage.success('验证成功')
      
      // 保存验证状态到sessionStorage
      sessionStorage.setItem('bankVerified', 'true')
      
      // 启动15分钟自动加密
      startAutoEncrypt()
    } else {
      ElMessage.error('验证码错误，请重新输入')
    }
  })
}

// 启动自动加密
function startAutoEncrypt() {
  // 如果已经有定时器在运行，不重复启动
  if (autoEncryptTimer.value) {
    return
  }
  
  // 如果没有倒计时值，设置15分钟倒计时
  if (encryptCountdown.value <= 0) {
    const totalSeconds = 15 * 60 // 15分钟 = 900秒
    encryptCountdown.value = totalSeconds
  }
  
  // 保存倒计时到sessionStorage
  sessionStorage.setItem('bankEncryptCountdown', encryptCountdown.value.toString())
  
  // 启动定时器，每秒更新倒计时
  autoEncryptTimer.value = setInterval(() => {
    encryptCountdown.value--
    
    // 更新sessionStorage中的倒计时
    sessionStorage.setItem('bankEncryptCountdown', encryptCountdown.value.toString())
    
    // 当倒计时为0时，自动加密
    if (encryptCountdown.value <= 0) {
      autoEncrypt()
    }
  }, 1000)
}

// 自动加密
function autoEncrypt() {
  bankVerified.value = false
  encryptCountdown.value = 0
  
  if (autoEncryptTimer.value) {
    clearInterval(autoEncryptTimer.value)
    autoEncryptTimer.value = null
  }
  
  // 清除sessionStorage中的验证状态
  sessionStorage.removeItem('bankVerified')
  sessionStorage.removeItem('bankEncryptCountdown')
  
  ElMessage.warning('辅助科目页面已自动加密，请重新验证')
  
  // 如果当前在辅助科目tab，自动切换回交易账号tab
  if (activeTab.value === 'bank') {
    activeTab.value = 'trade'
  }
}



// 检查当前用户是否有权限
function hasPermissionEmployee() {
  return currentUser.value.hasBankPermission
}

// 页面卸载时清理定时器
onUnmounted(() => {
  if (autoEncryptTimer.value) {
    clearInterval(autoEncryptTimer.value)
    autoEncryptTimer.value = null
  }
})

// 批量导入
// const bankImportDialog = ref(false)
// const bankImportText = ref('')
// function doBankImport() {
//   const lines = bankImportText.value.split('\n').map(l => l.trim()).filter(Boolean)
//   for (const line of lines) {
//     const [cardNo, safeCode] = line.split(',')
//     if (cardNo && safeCode) {
//       bankAccounts.value.unshift({ cardNo, safeCode })
//     }
//   }
//   bankImportDialog.value = false
//   bankImportText.value = ''
// }
// 服务器账号
const serverAccounts = ref([
  { name: '爬虫服务器A', ip: '192.168.1.10', status: '启用', remark: '主力采集' },
  { name: '爬虫服务器B', ip: '192.168.1.11', status: '禁用', remark: '备用' }
])
const serverSearch = ref('')
const filteredServerAccounts = computed(() => {
  if (!serverSearch.value) return serverAccounts.value
  return serverAccounts.value.filter(row =>
    row.name.includes(serverSearch.value) ||
    row.ip.includes(serverSearch.value) ||
    row.remark.includes(serverSearch.value)
  )
})
const serverDialog = ref({ visible: false, mode: 'add', form: { name: '', ip: '', remark: '' }, editIndex: -1 })
function openServerDialog(mode: 'add' | 'edit', row?: any, idx?: number) {
  serverDialog.value.mode = mode
  if (mode === 'add') {
    serverDialog.value.form = { name: '', ip: '', remark: '' }
    serverDialog.value.editIndex = -1
  } else if (row && typeof idx === 'number') {
    serverDialog.value.form = { ...row }
    serverDialog.value.editIndex = idx
  }
  serverDialog.value.visible = true
}
function saveServer() {
  const idx = serverDialog.value.editIndex
  if (serverDialog.value.mode === 'add') {
    serverAccounts.value.unshift({ ...serverDialog.value.form, status: '启用' })
  } else if (idx > -1) {
    serverAccounts.value[idx] = { ...serverDialog.value.form, status: serverAccounts.value[idx].status }
  }
  serverDialog.value.visible = false
}
function toggleServerStatus(row: any) { row.status = row.status === '启用' ? '禁用' : '启用' }
// 批量导入
// const serverImportDialog = ref(false)
// const serverImportText = ref('')
// function doServerImport() {
//   const lines = serverImportText.value.split('\n').map(l => l.trim()).filter(Boolean)
//   for (const line of lines) {
//     const [name, ip, remark] = line.split(',')
//     if (name && ip) {
//       serverAccounts.value.unshift({ name, ip, remark: remark || '', status: '启用' })
//     }
//   }
//   serverImportDialog.value = false
//   serverImportText.value = ''
// }
// 交易账号分页
const tradePage = ref({ current: 1, size: 10 })
const pagedTradeAccounts = computed(() => {
  const start = (tradePage.value.current - 1) * tradePage.value.size
  return filteredTradeAccounts.value.slice(start, start + tradePage.value.size)
})

// 可用的交易账号（排除当前账号，只显示对应站点）
const availableTradeAccounts = computed(() => {
  const currentAccount = tradeAccounts.value.find(acc => acc.account === tradeAccountSwitchDialog.value.currentAccount)
  if (!currentAccount) return []
  
  const availableAccounts = tradeAccounts.value.filter((acc: any) => 
    acc.account !== tradeAccountSwitchDialog.value.currentAccount && 
    acc.site === currentAccount.site &&
    acc.status === '启用'
  )
  
  // 去重处理，确保没有重复的账号
  return availableAccounts.filter((acc, index, self) => 
    index === self.findIndex(a => a.account === acc.account)
  )
})

// 用户转移时可用的交易账号（排除当前账号，只显示对应站点）
const availableTransferAccounts = computed(() => {
  const currentAccount = tradeAccounts.value.find(acc => acc.account === userTransferDialog.value.currentAccount)
  if (!currentAccount) return []
  
  const availableAccounts = tradeAccounts.value.filter((acc: any) => 
    acc.account !== userTransferDialog.value.currentAccount && 
    acc.site === currentAccount.site &&
    acc.status === '启用'
  )
  
  // 去重处理，确保没有重复的账号
  return availableAccounts.filter((acc, index, self) => 
    index === self.findIndex(a => a.account === acc.account)
  )
})
// 辅助科目分页
const bankPage = ref({ current: 1, size: 10 })
const pagedBankAccounts = computed(() => {
  const start = (bankPage.value.current - 1) * bankPage.value.size
  return filteredBankAccounts.value.slice(start, start + bankPage.value.size)
})
// 服务器账号分页
const serverPage = ref({ current: 1, size: 10 })
const pagedServerAccounts = computed(() => {
  const start = (serverPage.value.current - 1) * serverPage.value.size
  return filteredServerAccounts.value.slice(start, start + serverPage.value.size)
})
// 新增一个siteSelectValue用于el-select绑定
const siteSelectValue = ref('')
watch(
  () => activeSiteTab.value,
  (val) => {
    // 只要activeSiteTab是五个固定tab之一，下拉框清空
    if (["all", "mercari", "yahoo_auction", "yahoo_flea", "mercari_flea"].includes(val)) {
      siteSelectValue.value = ''
    } else {
      siteSelectValue.value = val
    }
  },
  { immediate: true }
)
watch(
  () => siteSelectValue.value,
  (val) => {
    if (val) {
      activeSiteTab.value = val
    }
  }
)
// 交易账号详情弹窗
const tradeDetailDialog = ref({ visible: false, data: null as any })
function showTradeDetail(row: any) {
  // 深拷贝数据，确保详情页面显示的是最新的数据
  tradeDetailDialog.value.data = JSON.parse(JSON.stringify(row))
  
  // 确保bindUsers是数组
  if (!tradeDetailDialog.value.data.bindUsers) {
    tradeDetailDialog.value.data.bindUsers = []
  }
  

  
  tradeDetailDialog.value.visible = true
}
// 跳转到交易账号绑定用户详情页面
function goToTradeUsersDetail(row: any) {
  router.push({
    name: 'tradeUsersDetail',
    params: { id: row.account }
  })
}

// 列表页绑定用户列溢出省略和悬浮全部
function getBindUserDisplay(users: any[]) {
  if (!users || users.length === 0) return '未绑定'
  const arr = users.map(u => (u.nickname ? `${u.nickname}（${u.id}）` : u.id))
  if (arr.length <= 2) return arr.join('，')
  return arr.slice(0, 2).join('，') + '...'
}
function getBindUserTooltip(users: any[]) {
  if (!users || users.length === 0) return '未绑定'
  return users.map(u => (u.nickname ? `${u.nickname}（${u.id}）` : u.id)).join('\n')
}
</script>

<style scoped>
.account-manage {
  padding: 16px;
}
.table-actions {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}
.site-tabs-bar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
.site-tabs-fixed {
  flex-shrink: 0;
}
.site-select {
  flex-shrink: 0;
}
.site-manage-btn {
  flex-shrink: 0;
  margin-left: 16px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.sites-display {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 4px;
}

.pay-accounts-container {
  width: 100%;
}

.pay-account-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.pay-account-item:last-child {
  margin-bottom: 0;
}
</style> 